/**
 * 
 */
package com;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import com.ericsson.otp.erlang.OtpErlangAtom;
import com.ericsson.otp.erlang.OtpErlangDecodeException;
import com.ericsson.otp.erlang.OtpErlangTuple;
import com.ericsson.otp.erlang.OtpInputStream;
import com.ericsson.otp.erlang.OtpOutputStream;

/**
 * @author vvorobyov
 *
 */
public class Host1 {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws OtpErlangDecodeException 
	 */
	public static void main(String[] args) throws IOException, OtpErlangDecodeException {
		System.setErr(new PrintStream(new FileOutputStream("c:/host.log.txt")));
		System.err.println(System.inheritedChannel());
		while(true){
			//System.err.println("Reading packet...");
			readPacket(System.in);
			//System.err.println("packet read.");
			//System.err.println("Sending packet...");
			sendPacket(System.out);
			System.out.flush();
			//System.err.println("packet sent.");
		}
	}

	private static void sendPacket(OutputStream out) throws IOException {
		OtpErlangTuple tuple = new OtpErlangTuple(new OtpErlangAtom[]{new OtpErlangAtom("ok"),new OtpErlangAtom("reply")});
		OtpOutputStream erlOut = new OtpOutputStream(tuple);
		byte[] buff=erlOut.toByteArray();
		intToBytes(buff.length+1,out);
		out.write(131);
		out.write(buff);
	}

	private static void readPacket(InputStream in) throws IOException, OtpErlangDecodeException {
		int size =intFromBytes(in);
		byte buff[]=new byte[size];
		for(int i=0;i<size;i++)
			buff[i]=(byte)in.read();//System.err.write(in.read());
		OtpInputStream erlIn = new OtpInputStream(buff);
		System.err.println(erlIn.read_any());
	}

	public static int intFromBytes(InputStream stream) throws IOException {
		int i = stream.read();
		//System.err.println(String.format("Byte read %s.",i));
		for(int k = 1; k < 4; k++) {
			i = Integer.rotateLeft(i, 8);
			//System.err.println(String.format("Byte << %s.",i));
			i |= stream.read();
			//System.err.println(String.format("Byte i |= stream.read() %s.",i));
		}
		return i;
	}
	
	public static void intToBytes(int i, OutputStream stream) throws IOException {
		for(int k = 0; k < 4; k++) {
			i = Integer.rotateLeft(i, 8);
			stream.write(i);
		}
	}
}
